/**
 * 写入缓存
 *
 * 全部都会加密,
 * 都会先转成json
 *
 * expired 过期时间 s
 *  -1 永不过期
 *
 */
import base64 from './base64'
import store from '@/store'

export const save = (key, data, expired = -1) => {
  if (data === null) {
    return
  }
  const obj = {
    data,
    expired: expired > -1 ? expired * 1000 + new Date().getTime() : -1
  }
  window.localStorage.setItem(key, base64.encode(obj))
}

export const get = (key) => {
  const value = window.localStorage.getItem(key)
  if (value === null) {
    return null
  }
  const obj = base64.parse(value)
  const { data, expired } = obj
  if (expired > -1 && expired < new Date().getTime()) {
    // console.log(expired, new Date().getTime())
    remove(key)
    return null
  }
  return data
}

export const remove = (key) => {
  return window.localStorage.removeItem(key)
}

/**
 * clear all cache
 * but, exclusive token & info(service menu => isMerchant)
 */
export const removeAll = () => {
  const token = store.getters['ExecUser/token']
  const info = store.getters['ExecUser/info']
  window.localStorage.clear()
  store.dispatch('ExecUser/login', token).then()
  store.dispatch('ExecUser/set_info', info).then()
}
